<?php
namespace FastPHP\Core;

use FastPHP\Library\Request;

class Controller
{
    protected $data = [];
    protected $jumpTpl = 'FastPHP/tpl/dispatch_jump.tpl';
    protected $beforeActionList = [];

    public function __construct()
    {
        // 控制器初始化
        if (method_exists($this, 'initialize')) {
            $this->initialize();
        }
        $this->beforeAction();
    }

    // 前置操作
    protected function beforeAction()
    {
        foreach ($this->beforeActionList as $method) {
            if (method_exists($this, $method)) {
                $this->$method();
            }
        }
    }

    // 赋值到视图
    public function assign($name, $value)
    {
        $this->data[$name] = $value;
    }

    // 渲染视图
    public function display($view = null)
    {
        extract($this->data);
        
        // 如果没有指定视图，自动推断
        if ($view === null) {
            $controller = $this->getControllerName();
            $action = $this->getActionName();
            $view = strtolower($controller) . '/' . $action;
        }
        
        // 构建视图文件路径
        $group = $this->getGroupName();
        $viewFile = ROOT_PATH . $group . '/app/view/' . $view . '.php';
        
        if (file_exists($viewFile)) {
            include $viewFile;
        } else {
            throw new \FastPHP\Core\HttpException("视图文件 {$viewFile} 不存在", 404);
        }
    }
    
    // 获取控制器名称
    protected function getControllerName()
    {
        // 从路由解析结果中获取控制器名称
        if (isset($GLOBALS['_ROUTER_CONTROLLER'])) {
            return strtolower($GLOBALS['_ROUTER_CONTROLLER']);
        }
        
        // 从类名中获取
        $class = get_class($this);
        $parts = explode('\\', $class);
        $controller = end($parts);
        return strtolower(str_replace('Controller', '', $controller));
    }
    
    // 获取分组名称
    protected function getGroupName()
    {
        // 从路由解析结果中获取分组名称
        if (isset($GLOBALS['_ROUTER_GROUP'])) {
            return $GLOBALS['_ROUTER_GROUP'];
        }
        
        // 从APP_GROUP常量获取
        if (defined('APP_GROUP')) {
            return APP_GROUP;
        }
        
        // 从URL中获取分组名称
        $pathInfo = $_SERVER['PATH_INFO'] ?? '';
        $pathParts = explode('/', trim($pathInfo, '/'));
        
        if (isset($pathParts[0])) {
            return $pathParts[0];
        }
        
        return 'home';
    }
    
    // 获取操作名称
    protected function getActionName()
    {
        // 从路由解析结果中获取操作名称
        if (isset($GLOBALS['_ROUTER_ACTION'])) {
            return $GLOBALS['_ROUTER_ACTION'];
        }
        
        // 从URL中获取操作名称
        $pathInfo = $_SERVER['PATH_INFO'] ?? '';
        $pathParts = explode('/', trim($pathInfo, '/'));
        
        // 如果URL中有操作名称，使用它
        if (isset($pathParts[1])) {
            return $pathParts[1];
        }
        
        // 否则从debug_backtrace中获取
        $trace = debug_backtrace();
        foreach ($trace as $call) {
            if (isset($call['function']) && 
                $call['function'] !== 'display' && 
                $call['function'] !== 'getActionName' &&
                $call['function'] !== '__construct' &&
                $call['function'] !== 'beforeAction') {
                return $call['function'];
            }
        }
        
        return 'index';
    }

    // success跳转
    protected function success($msg = '操作成功', $url = '', $data = '', $wait = 3, $code = 1)
    {
        $this->dispatchJump($msg, $url ?: ($_SERVER['HTTP_REFERER'] ?? '/'), $data, $wait, $code, true);
    }

    // error跳转
    protected function error($msg = '操作失败', $url = '', $data = '', $wait = 3, $code = 0)
    {
        $this->dispatchJump($msg, $url ?: 'javascript:history.back(-1);', $data, $wait, $code, false);
    }

    // 跳转核心
    protected function dispatchJump($msg, $url, $data, $wait, $code, $success, $lock = false)
    {
        $jumpConf = config('app.jump', []);
        $jump_title = $jumpConf['title'] ?? '提示信息';
        $jump_dir = $jumpConf['direction'] ?? 'ltr';
        $wait_text = $jumpConf['wait_text'] ?? '页面将在 {wait} 秒后自动跳转...';
        $btn_text = $jumpConf['btn_text'] ?? '立即跳转';
        $lock_text = $jumpConf['lock_text'] ?? '本页已锁定';
        $tpl = $jumpConf['template'] ?? $this->jumpTpl;
        $wait_text = str_replace('{wait}', (int)$wait, $wait_text);

        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
            'lock' => $lock,
            'jump_title' => $jump_title,
            'jump_dir' => $jump_dir,
            'wait_text' => $wait_text,
            'btn_text' => $btn_text,
            'lock_text' => $lock_text,
        ];
        $currentUrl = $_SERVER['REQUEST_URI'] ?? '';
        $noJump = empty($url) || $url === $currentUrl;
        if (request()->isAjax()) {
            response()->json($result);
        } else {
            extract($result);
            if (!file_exists(ROOT_PATH . $tpl)) {
                echo "<meta charset='utf-8'><title>{$jump_title}</title><div style='margin:100px auto;width:400px;text-align:center;'><h2>{$msg}</h2>";
                if ($lock || $noJump) {
                    echo "<p style='color:#e74c3c'>{$lock_text}</p>";
                } else {
                    echo "<p><span id='wait'>{$wait}</span>{$wait_text}<br><a id='href' href='{$url}'>{$btn_text}</a></p>";
                    echo "<script>setTimeout(function(){location.href=document.getElementById('href').href},{$wait}000);</script>";
                }
                echo "</div>";
                exit;
            }
            include ROOT_PATH . $tpl;
            exit;
        }
    }

    // lock方法，显示锁定提示，不跳转无按钮无时间
    protected function lock($msg = '页面已锁定', $data = '', $code = 0)
    {
        $this->dispatchJump($msg, '', $data, 0, $code, false, true);
    }

    // 设置跳转模板
    protected function setJumpTpl($tpl)
    {
        $this->jumpTpl = $tpl;
    }

    // 空操作
    public function _empty($action, ...$args)
    {
        // 记录访问信息
        $this->assign('action', $action);
        $this->assign('args', $args);
        $this->assign('url', request()->url());
        $this->assign('ip', request()->ip());
        
        // 显示自定义404页面
        $this->display('empty/404');
    }

    // 魔术方法，自动调用空操作
    public function __call($name, $args)
    {
        if (method_exists($this, '_empty')) {
            return call_user_func_array([$this, '_empty'], array_merge([$name], $args));
        }
        exit("方法 {$name} 不存在");
    }
} 